;
(function() {
  new Vue({
    el: '#YY-notice',
    data: {
      curDate: hlDateUtil.formatDate(new Date(), 'yyyy-MM-dd'),
      deadTimeDate: null,
      billbeginDate: null,
      billendDate: null,
      billNo: null,
      user: null,
      billId: hlUrlUtil.GetQueryString('id'),
      data: [],
      projectData: {
        companyName: '',
        name: '',
        date: '',
        bankAccounts: ''
      },
      num: 0,
      contractData: [],
      units: null,
      expenses: [],
      addExpenses: [],
      amountData: {
        expenses: []
      }
    },
    filters: {
      formatDate: function(time) {
        if (!time) return '';
        var rex = /-/gi;
        if (rex.test(time)) return time;
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      toFixed2: function(n) {
        return Number(n).toFixed(2)
      },
      spceVal: function (n) {
        if (!n) return '';
        var temp = n.split('');
        var sp = 0;
        for (var i = 0; i < temp.length; i++) {
          if (i%4 == 0) {
            temp.splice(i+4+sp,0, ' ')
            sp++
          }
        }
        return temp.join('')
      }
    },
    computed: {
      total: function() {
        var result = 0;
        this.expenses.map(function(item) {
          result += Number(item.total)
        })
        this.addExpenses.map(function(item) {
          if (item.total) result += Number(item.total)
        })
        return result
      }
    },
    methods: {
      //联动银行
      linkBank: function(i) {
        this.num = i;
      },
      // 获取当前用户信息
      getCurUser: function() {
        if (window.localStorage.getItem('userMes')) {
          this.user = JSON.parse(window.localStorage.getItem('userMes')).name
        }
      },
      //获取项目
      getProjectMes: function() {
        var projectId = window.localStorage.getItem('PROJECTID');
        var _this = this;
        hlhttp.get({
          url: 'project',
          data: {
            project_id: projectId
          },
          success: function(res) {
            _this.projectData = {
              companyName: res.pcompany,
              name: res.name,
              bankAccounts: res.bankAccounts ? res.bankAccounts.split(',') : null,
              bankName: res.bankNames ? res.bankNames.split(',') : null,
              accountNames: res.accountNames ? res.accountNames.split(',') : null,
              date: hlDateUtil.formatUTCDate(new Date().getTime(), 'yyyy-MM-dd'),
              legalName: res.legalName,
              addrees: res.provinceName + ' ' + res.cityName + ' ' + res.districtName + ' ' + res.address,
              rpersonPhone: res.rpersonPhone,
              rpersonName: res.rpersonName
            }
          }
        })
      },
      //获取合同信息
      getContractMes: function() {
        var id = hlUrlUtil.GetQueryString('aid');
        var self = this;
        hlhttp.get({
          url: 'contract',
          data: {
            id: id
          },
          success: function(res) {
            self.contractData = {
              projectName: res.projectName,
              mCode: res.mCode,
              units: res.units,
              zlfCompany: res.zlfCompany,
              acreage: res.rentAcreage,
              rentPrice: res.rentPrice
            }

            for (var i = 0; i < self.amountData.expenses.length; i++) {
              for (var j = 0; j < res.expenses.length; j++) {
                if (self.amountData.expenses[i].name === res.expenses[j].expenseName) {
                  self.amountData.expenses[i].expense = res.expenses[j].expense
                }
              }
            }

            // 调整单元的数据
            var unitsArr = [];
            res.units.map(function(_item) {
              var obj = {}
              if (_item.positions.length == 0) {
                obj = {
                  'buildingName': _item.buildingName,
                  'floorNum': _item.floorNum,
                  'unitName': _item.unitName,
                  'positionName': ''
                }
                unitsArr.push(obj)
              }
              if (_item.positions.length) {
                // 工位类型
                if (_item.unitType === 'WP') {
                  obj = {
                    'buildingName': _item.buildingName,
                    'floorNum': _item.floorNum,
                    'unitName': _item.unitName,
                    'positionName': '工位' + _item.positions.length + '个'
                  }
                  unitsArr.push(obj)
                }
                // 车位类型
                if (_item.unitType === 'ST') {
                  obj = {
                    'buildingName': _item.buildingName,
                    'floorNum': _item.floorNum,
                    'unitName': _item.unitName,
                    'positionName': '车位' + _item.positions.length + '个'
                  }
                  unitsArr.push(obj)
                }
              }
            })
            self.units = unitsArr
          }
        })
      },
      //获取账单信息
      getAccountsMes: function() {
        var _this = this;
        hlhttp.get({
          url: 'bill,expenses,transactions',
          data: {
            bill_id: _this.billId
          },
          success: function(res) {
            _this.deadTimeDate = hlDateUtil.formatUTCDate(res.deadlineDate, 'yyyy-MM-dd');
            _this.billNo = res.no;
            _this.billbeginDate = res.beginDate;
            _this.billendDate = res.endDate;
            _this.getContractMes()
            _this.getExpenseMes()
          }
        })
      },
      //获取缴费信息
      getExpenseMes: function() {
        var self = this;
        hlhttp.get({
          url: 'bill/expenses',
          data: {
            bill_id: self.billId
          },
          success: function(data) {
            var arr = [];
            data.map(function(_item) {
              var obj = {
                'beginDate': self.billbeginDate,
                'endDate': self.billendDate
              }
              obj.name = _item.name
              obj.id = _item.id
              obj.currency = 'RMB'
              obj.memo = ''
              obj.amount = _item.amountTPay + _item.lateFeeTPay - _item.lateFeeDerate - _item.amountDerate
              obj.payAmount = _item.amountTPay + _item.lateFeeTPay - _item.lateFeeDerate - _item.amountDerate - _item.amountRefund + _item.refundPayed
              obj.surcharge = _item.lateFeeTPay
              obj.total = _item.amountTPay + _item.lateFeeTPay - _item.lateFeeDerate - _item.amountDerate;
              arr.push(obj)
            })
            self.expenses = arr;
          }
        })
      },
      //as
      tdhover: function() {
        var oinput;
        $('td[data-focus=true]').on('focus', 'li', function(event) {
          oinput = $(this).text()
        });
        $('td[data-focus=true]').on('blur', 'li', function(event) {
          if ($(this).text() == '') {
            $(this).text(oinput)
          }
        });
      },
      addBill: function() {
        var self = this;
        $(document).on('click', '.js-add-bill', function(event) {
          var obj = {
            id: '',
            name: '',
            beginDate: '',
            endDate: '',
            currency: '',
            amount: '',
            payAmount: '',
            surcharge: '',
            total: '',
            memo: ''
          }
          self.addExpenses.push(obj)
        })
      },
      delBill: function() {
        var self = this;
        $(document).on('click', '.js-del-bill', function(event) {
          // 每次从最后一个新增的账单开始删除
          self.addExpenses.splice(self.addExpenses.length - 1, 1)
        })
      },
      printBill: function() {
        var self = this;
        $(document).on('click', '.js-print', function(event) {

          self.addExpenses.map(function(item) {
            self.expenses.push(item)
          })
          self.addExpenses = [];

          // 打印
          setTimeout(function() {
            var bdhtml = window.document.body.innerHTML;
            var prnhtml = $('.pt-wrap').html()
            window.document.body.innerHTML = prnhtml;
            window.print();
            window.document.body.innerHTML = bdhtml;
          }, 500)
        });
      },
      // 导出PDF
      exportPDF: function() {
        var self = this;
        var doctypeHtml = '<!DOCTYPE html>' +
              '<html lang="en">' +
              '<head>' +
                '<meta charset="UTF-8"></meta>' +
                '<link rel="stylesheet" href="/opt/haolou/wbuild-page-saas-pc/com.fenzhitech.haolou-saas/wbuild-saas-pc/styles/libs/bootstrap_3.3.7.css"></link>' +
                '<link rel="stylesheet" href="/opt/haolou/wbuild-page-saas-pc/com.fenzhitech.haolou-saas/wbuild-saas-pc/styles/libs/font.css"></link>' +
                '<link rel="stylesheet" href="/opt/haolou/wbuild-page-saas-pc/com.fenzhitech.haolou-saas/wbuild-saas-pc/styles/app/blue/blue.min.css"></link>' +
              '</head>'+
              '<body>'

        var getPDFUrl = function(){
          var ctxHtml = $('.pt-wrap').html()
          var modelHtml = doctypeHtml + ctxHtml + '</body></html>'
          modelHtml = modelHtml.replace(window.location.protocol+'//s.1hello.com/wbuild-saas-pc','/opt/haolou/wbuild-page-saas-pc/com.fenzhitech.haolou-saas/wbuild-saas-pc')

          $.ajax({
            url:convert2pdfApi,
            type: 'post',
            data:{'html_str':modelHtml},
            headers:{token:Cookies.get("token")},
            success:function(data){
              window.open(data.url)
            }
          })
        }

        $(document).on('click', '.export-pdf', function(event) {
          // 将新增加的账单项添加到原有账单项中
          self.addExpenses.map(function(item) {
            self.expenses.push(item)
          })
          self.addExpenses = [];
          setTimeout(function(){
            getPDFUrl()
          },500)
        })
      },
    },
    mounted: function() {
      hlSelectUi()
      this.printBill()
      this.exportPDF()
      this.addBill()
      this.delBill()
      this.getCurUser()
      this.getProjectMes()
      this.getAccountsMes()
    }
  })
}())
